# -*- coding:utf-8 -*-

# @Time : 2022/11/22 15:11
# @Author : 快乐的小猴子
# @Version : 
# @Function : 

import os
import time
from YouMeiPics.conf import settings
from lxml import etree
from YouMeiPics.PubBases import PublicBases


class PhonePictures:
    """
    手机壁纸类
    """

    def get_page_num(self, html):
        '''
        获取总页码
        :param html:
        :return:
        '''
        et = etree.HTML(html)
        page_num = et.xpath('//div[@id="pageNum"]/a[3]/@href')[0].split('_')[-1].split('.')[0]
        return page_num

    def verf_dir(self, pic_type_name):
        '''
        校验图片存储路径是否存在，不存在则创建
        :return:
        '''
        pics_path = os.getcwd() + '\\pictures\\{}\\'.format(pic_type_name)
        if not os.path.exists(pics_path):
            os.makedirs(pics_path)
        return pics_path

    def get_exist_pics_name(self, pic_path):
        '''
        获取图片文件夹中已经存在的图片名称
        :param pic_path:
        :return:
        '''
        pic_names = os.listdir(pic_path)
        pic_name_list = []
        for name in pic_names:
            pic_name = name.strip()[:-4]
            pic_name_list.append(pic_name)
        return pic_name_list

    def get_pics(self, html, pic_type_name):
        '''
        一页图片下载
        :param html:
        :return:
        '''
        et = etree.HTML(html)
        big_pic_name = et.xpath('//div[@class="item_list infinite_scroll"]/div/div[1]/div[@class="img"]/a/img/@alt')
        big_pic_url = et.xpath('//div[@class="item_list infinite_scroll"]/div/div[1]/div[@class="img"]/a/img/@data-original')
        for i in range(0, len(big_pic_name)):
            print('{} 正在下载中......'.format(big_pic_name[i]))
            pics_path = self.verf_dir(pic_type_name)
            pic_name_list = self.get_exist_pics_name(pics_path)
            if big_pic_name[i].strip() in pic_name_list:
                print('{} 已经存在！！！'.format(big_pic_name[i]))
                continue
            else:
                PublicBases().down_pics_send(big_pic_name[i], big_pic_url[i], pics_path)
                time.sleep(0.5)
                print('{} {} 下载完成 !'.format(i + 1, big_pic_name[i]))

    def more_pics_down(self, page_num, pic_type_name, in_seq2):
        '''
        所有图片页数据下载
        :param page_num:
        :param html:
        :return:
        '''
        for num in range(1, int(page_num) + 1):
            try:
                next_url = '{}/bizhitupian/{}/index_{}.htm'.format(settings.url, settings.pic_bztp_urls[in_seq2],
                                                                   str(num))
                html = PublicBases().send(next_url)
                self.get_pics(html, pic_type_name)
            except Exception as e:
                print(e)
            print('>>>>>> 第 {} 页 图片下载完成 0_0 !!! >>>>>>>'.format(num))

